package main

import (
	"fmt"
	"github.com/hepeichun/mdns"
	"log"
	"net"
	"time"
)

const (
	pluginName    = "hepeichun@mdns"
	pluginVersion = 0x00010000
)

type Mdns struct {
	service   string
	duration  int64
	timeout   int64
	hasSearch bool
}

func init() {
}

// Load 不可以删除，否则会导致无法注册插件
func Load(register func(name string, version uint64) error) error {
	err := register(pluginName, pluginVersion)
	if err != nil {
		log.Println(err.Error())
		return err
	}
	log.Printf("loading %s plugin\n", pluginName)
	run()
	return nil
}

// Unload 插件卸载实现动作
func Unload() error {
	fmt.Printf("unload %s, version: 0x%x\n", pluginName, pluginVersion)
	return nil
}

func run() {

}

func test() {
	Lookup("_device-info._tcp.", 10, func(Name string, Host string, Addr net.IP, AddrV4 net.IP, AddrV6 net.IP, Port int, InfoFields []string, Info string, TTL int) {
		fmt.Printf("	名称: %s \n	地址: %s \n	IPv4: %s \n	IPv6: %s \n	主机: %s \n	端口: %d\n	信息字段: %s\n	信息: %s\n	TTL: %d\n",
			Name, Addr, AddrV4, AddrV6, Host, Port, InfoFields, Info, TTL)
	})

	time.Sleep(time.Second * 10)
}

func Lookup(service string, duration int,
	callback func(Name string, Host string, Addr net.IP, AddrV4 net.IP, AddrV6 net.IP, Port int, InfoFields []string, Info string, TTL int)) bool {

	entriesCh := make(chan *mdns.ServiceEntry, 8)
	go func() {
		for entry := range entriesCh {
			fmt.Println("发现设备")
			callback(entry.Name, entry.Host, entry.Addr, entry.AddrV4, entry.AddrV6, entry.Port, entry.InfoFields, entry.Info, entry.TTL)
		}
	}()

	dateTime := time.Now().Unix()
	hasSearch := true

	var timeout int64
	if duration > 0 {
		timeout = dateTime + int64(duration)
	} else {
		duration = 0
	}

	go func() {
		for hasSearch {
			err := mdns.Lookup(service, entriesCh)
			if err != nil {
				fmt.Println(err)
				//return true, err
			}
			if (duration != 0) && (timeout < time.Now().Unix()) {
				hasSearch = false
			}
			time.Sleep(time.Millisecond * 100)
		}
		close(entriesCh)
		log.Println("结束检索mdns")
	}()

	return hasSearch
}
